<template>
  <div class="caregiver-dashboard">
    <!-- 顶部欢迎提示语 -->
    <div class="welcome-section">
      <h1 class="welcome-title">亲爱的{{ userInfo.name }}护工，欢迎回来！</h1>
      <p class="welcome-subtitle">今天也要用爱心和专业守护每一位长者哦~ 💕</p>
    </div>

    <!-- 天气模块 -->
    <div class="weather-section">
      <el-card class="weather-card">
        <template #header>
          <div class="weather-header">
            <i class="el-icon-sunny"></i>
            <span>天气信息</span>
            <div class="date-navigation">
              <el-button 
                size="small" 
                @click="previousDay" 
                :disabled="currentDateIndex === 0"
                circle
              >
                <i class="el-icon-arrow-left"></i>
              </el-button>
              <span class="date-display">{{ displayDate }}</span>
              <el-button 
                size="small" 
                @click="nextDay" 
                :disabled="currentDateIndex === 2"
                circle
              >
                <i class="el-icon-arrow-right"></i>
              </el-button>
            </div>
          </div>
        </template>
        <div v-if="weatherData" class="weather-content">
          <div class="weather-main">
            <div class="temperature">{{ weatherData.temperature }}°C</div>
            <div class="weather-info">
              <div class="weather-desc">{{ weatherData.weather }}</div>
              <div class="weather-detail">
                <span>湿度: {{ weatherData.humidity }}%</span>
                <span>风向: {{ weatherData.wind }}</span>
              </div>
              <!-- 新增详细信息 -->
              <div class="weather-details-grid">
                <div class="detail-item">
                  <i class="el-icon-wind-power"></i>
                  <span class="detail-label">空气质量</span>
                  <span class="detail-value">{{ getAQIDisplay(weatherData.aqi) }}</span>
                </div>
                <div class="detail-item">
                  <i class="el-icon-cloudy"></i>
                  <span class="detail-label">降水概率</span>
                  <span class="detail-value">{{ weatherData.precipitation }}</span>
                </div>
                <div class="detail-item">
                  <i class="el-icon-thermometer"></i>
                  <span class="detail-label">体感温度</span>
                  <span class="detail-value">{{ weatherData.feelsLike }}°C</span>
                </div>
                <div class="detail-item">
                  <i class="el-icon-sunrise"></i>
                  <span class="detail-label">紫外线</span>
                  <span class="detail-value">{{ weatherData.uvIndex }}</span>
                </div>
                <div class="detail-item">
                  <i class="el-icon-sunny"></i>
                  <span class="detail-label">防晒建议</span>
                  <span class="detail-value">{{ weatherData.spf }}</span>
                </div>
              </div>
            </div>
          </div>
          <div class="weather-tips">
            <p>{{ weatherData.careTips || weatherTips }}</p>
          </div>
        </div>
        <div v-else class="weather-loading">
          <el-skeleton :rows="3" animated />
        </div>
      </el-card>
    </div>

    <!-- 健康宣传话语 -->
    <div class="inspiration-section">
      <el-card class="inspiration-card">
        <div class="inspiration-content">
          <i class="el-icon-chat-dot-round"></i>
          <div class="inspiration-text">
            <h3>养老中心健康宣传</h3>
            <p>{{ currentInspiration }}</p>
          </div>
        </div>
      </el-card>
    </div>

    <!-- AI助手 -->
    <div class="ai-assistant-section">
      <el-card class="ai-card">
        <div class="ai-content">
          <div class="ai-avatar">
            <i class="el-icon-chat-line-round"></i>
          </div>
          <div class="ai-message">
            <p class="ai-greeting">嗨~ {{ userInfo.name }}护工！我是你的AI小助手~ 🌟</p>
            <p class="ai-question">今天有什么需要我帮忙的吗？比如：</p>
            <ul class="ai-suggestions">
              <li>📝 记录长者健康状况</li>
              <li>💊 查看用药提醒</li>
              <li>🍽️ 安排今日餐饮</li>
              <li>👥 了解护理注意事项</li>
            </ul>
            <div class="ai-input">
              <el-input
                v-model="aiInput"
                placeholder="告诉我你需要什么帮助吧~"
                @keyup.enter="handleAiQuery"
                :disabled="aiLoading"
              >
                <template #append>
                  <el-button 
                    @click="handleAiQuery" 
                    type="primary"
                    :loading="aiLoading"
                    :disabled="aiLoading"
                  >
                    {{ aiLoading ? '思考中...' : '发送' }}
                  </el-button>
                </template>
              </el-input>
            </div>
            
            <!-- 加载提示 -->
            <div v-if="aiLoading" class="ai-loading">
              <div class="loading-content">
                <div class="loading-dots">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
                <p class="loading-text">{{ loadingMessages[currentLoadingMessage] }}</p>
              </div>
            </div>
            
            <!-- AI回复 -->
            <div v-if="aiResponse && !aiLoading" class="ai-response">
              <p>{{ aiResponse }}</p>
            </div>
            
            <!-- 错误提示 -->
            <div v-if="aiError" class="ai-error">
              <p>😅 哎呀，网络有点小调皮~ 请稍后再试，或者直接联系管理员哦！</p>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import axios from '@/api/axios'

// 用户信息
const userInfo = reactive(JSON.parse(localStorage.getItem('userInfo') || '{}'))

// 天气数据
const weatherData = ref(null)

// 日期切换相关
const currentDateIndex = ref(1) // 0: 昨天, 1: 今天, 2: 明天
const weatherDataList = ref([null, null, null]) // 存储三天的天气数据

// 健康宣传话语列表
const inspirations = [
  "用爱心和专业守护每一位长者，让温暖传递到每个角落 ❤️",
  "细心观察，耐心倾听，您的关怀是长者最好的良药 🌟",
  "每一次微笑，每一次问候，都是对长者最好的陪伴 🌈",
  "专业护理，用心服务，让长者的晚年生活更加美好 🌸",
  "您的辛勤付出，为长者带来了健康和快乐，感谢您的奉献！ 🌟"
]

// 当前显示的健康宣传话语
const currentInspiration = ref('')

// AI助手相关
const aiInput = ref('')
const aiResponse = ref('')
const aiLoading = ref(false)
const aiError = ref(false)
const aiMessages = ref([])

// 俏皮可爱的加载提示消息
const loadingMessages = ref([
  "✨ 正在努力思考中... 让我想想怎么更好地帮助你~",
  "💭 小脑瓜飞速运转中... 马上就有答案啦！",
  "🌟 正在为你精心准备回答... 请稍等片刻哦~",
  "💖 正在调取最温暖的答案... 马上就好！",
  "🌈 正在编织最贴心的回复... 稍等一下下~"
])

const currentLoadingMessage = ref(0)

// 显示日期计算
const displayDate = computed(() => {
  const today = new Date()
  const targetDate = new Date(today)
  targetDate.setDate(today.getDate() + (currentDateIndex.value - 1))
  
  const options = { month: 'long', day: 'numeric', weekday: 'long' }
  const dateStr = targetDate.toLocaleDateString('zh-CN', options)
  
  if (currentDateIndex.value === 0) return `昨天 (${dateStr})`
  if (currentDateIndex.value === 1) return `今天 (${dateStr})`
  if (currentDateIndex.value === 2) return `明天 (${dateStr})`
  return dateStr
})

// 根据AQI值获取空气质量显示
const getAQIDisplay = (aqi) => {
  const aqiValue = parseInt(aqi)
  if (aqiValue <= 50) return '优'
  if (aqiValue <= 100) return '良'
  if (aqiValue <= 150) return '轻度污染'
  if (aqiValue <= 200) return '中度污染'
  return '重度污染'
}

// 根据天气数据生成护理建议
const weatherTips = computed(() => {
  if (!weatherData.value) return ''
  
  const temp = parseInt(weatherData.value.temperature)
  const weather = weatherData.value.weather.toLowerCase()
  
  if (temp < 10) {
    return "天气较冷，请注意为长者添加衣物，保持室内温暖，预防感冒。"
  } else if (temp > 28) {
    return "天气炎热，请确保长者补充足够水分，避免中暑，适当开启空调。"
  } else if (weather.includes('雨')) {
    return "雨天路滑，请提醒长者注意安全，减少外出活动。"
  } else if (weather.includes('风')) {
    return "风力较大，请注意长者保暖，避免受凉。"
  } else {
    return "天气适宜，适合长者进行适度的户外活动。"
  }
})

// 日期切换方法
const previousDay = () => {
  if (currentDateIndex.value > 0) {
    currentDateIndex.value--
    updateWeatherData()
  }
}

const nextDay = () => {
  if (currentDateIndex.value < 2) {
    currentDateIndex.value++
    updateWeatherData()
  }
}

// 更新天气数据显示
const updateWeatherData = () => {
  // 这里可以扩展为调用不同日期的天气API
  // 目前使用模拟数据来展示功能
  if (!weatherDataList.value[currentDateIndex.value]) {
    // 生成模拟数据
    const baseTemp = 25
    const variations = [-3, 0, 2] // 昨天、今天、明天的温度变化
    const weatherTypes = ['多云', '晴', '小雨']
    
    weatherDataList.value[currentDateIndex.value] = {
      temperature: (baseTemp + variations[currentDateIndex.value]).toString(),
      weather: weatherTypes[currentDateIndex.value],
      humidity: (60 + currentDateIndex.value * 5).toString(),
      wind: ['北风2级', '东南风3级', '东风4级'][currentDateIndex.value]
    }
  }
  
  weatherData.value = weatherDataList.value[currentDateIndex.value]
}

// 获取天气数据
const fetchWeather = async () => {
  try {
    const res = await axios.get('/api/weather/current')
    // 将今天的天气数据存储到列表中
    weatherDataList.value[1] = res.data
    weatherData.value = res.data
  } catch (error) {
    console.error('获取天气数据失败:', error)
    // 使用模拟数据
    const mockData = {
      temperature: '25',
      weather: '晴',
      humidity: '65',
      wind: '东南风3级'
    }
    weatherDataList.value[1] = mockData
    weatherData.value = mockData
  }
}

// 随机选择健康宣传话语
const getRandomInspiration = () => {
  const randomIndex = Math.floor(Math.random() * inspirations.length)
  currentInspiration.value = inspirations[randomIndex]
}

// 处理AI助手查询
const handleAiQuery = async () => {
  if (!aiInput.value.trim()) {
    ElMessage.warning('请输入您的问题哦~')
    return
  }

  aiLoading.value = true
  aiError.value = false
  aiResponse.value = ''
  
  // 开始加载消息轮换
  const loadingInterval = setInterval(() => {
    currentLoadingMessage.value = (currentLoadingMessage.value + 1) % loadingMessages.value.length
  }, 3000)
  
  try {
    // 使用自定义超时配置
    const res = await axios.post('/api/ai/assistant', {
      query: aiInput.value,
      role: 'caregiver'
    }, {
      timeout: 60000 // 延长超时时间到60秒
    })
    
    // 确保正确获取响应数据
    if (res.data && res.data.data) {
      aiResponse.value = res.data.data
    } else if (res.data) {
      aiResponse.value = res.data
    } else {
      aiResponse.value = "✨ 收到你的问题啦！虽然我这边有点小状况，但你的关心和爱心已经传递到了~ 💕"
    }
    
    aiInput.value = '' // 清空输入框
  } catch (error) {
    console.error('AI助手请求失败:', error)
    aiError.value = true
    
    // 更友好的错误提示
    if (error.code === 'ECONNABORTED' || error.message.includes('timeout')) {
      aiResponse.value = "⏰ 哎呀，思考时间有点长呢~ 网络小调皮了一下！\n\n" +
        "💖 不过没关系，你的问题我已经收到啦！\n" +
        "✨ 可能是网络在休息，稍等一下再试试吧~\n" +
        "💝 或者你可以先问问其他问题，我随时都在这里等你！"
    } else {
      aiResponse.value = "😅 网络有点小调皮呢~ 不过别担心！\n\n" +
        "💕 你的爱心和耐心是最重要的！\n" +
        "✨ 稍等一下再试试，或者直接联系管理员哦~\n" +
        "🌟 我永远在这里为你服务！"
    }
  } finally {
    aiLoading.value = false
    clearInterval(loadingInterval)
    currentLoadingMessage.value = 0
  }
}

onMounted(() => {
  fetchWeather()
  getRandomInspiration()
  
  // 每30分钟更新一次天气
  setInterval(fetchWeather, 30 * 60 * 1000)
  
  // 每2小时更换一次健康宣传话语
  setInterval(getRandomInspiration, 2 * 60 * 60 * 1000)
})
</script>

<style scoped>
.caregiver-dashboard {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.welcome-section {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 15px;
  color: white;
}

.welcome-title {
  font-size: 2.2em;
  margin-bottom: 10px;
  font-weight: 600;
}

.welcome-subtitle {
  font-size: 1.2em;
  opacity: 0.9;
}

.weather-section {
  margin-bottom: 30px;
}

.weather-card {
  border-radius: 15px;
}

.weather-header {
  display: flex;
  align-items: center;
  gap: 10px;
  font-weight: 600;
  color: #409EFF;
}

.weather-header i {
  font-size: 1.2em;
}

.weather-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.weather-main {
  display: flex;
  align-items: center;
  gap: 20px;
}

.temperature {
  font-size: 3em;
  font-weight: bold;
  color: #409EFF;
}

.weather-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.weather-desc {
  font-size: 1.3em;
  font-weight: 600;
}

.weather-detail {
  display: flex;
  gap: 15px;
  font-size: 0.9em;
  color: #666;
}

/* 天气详细信息网格 */
.weather-details-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
  margin-top: 15px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 10px;
  border: 1px solid #e9ecef;
}

.detail-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  padding: 10px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.detail-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.detail-item i {
  font-size: 1.5em;
  color: #409EFF;
  margin-bottom: 8px;
}

.detail-label {
  font-size: 0.8em;
  color: #666;
  margin-bottom: 4px;
  font-weight: 500;
}

.detail-value {
  font-size: 1em;
  font-weight: 600;
  color: #333;
}

.weather-tips {
  flex: 1;
  margin-left: 30px;
  padding: 15px;
  background: #f0f9ff;
  border-radius: 10px;
  border-left: 4px solid #409EFF;
}

.weather-tips p {
  margin: 0;
  color: #333;
  font-weight: 500;
}

.inspiration-section {
  margin-bottom: 30px;
}

.inspiration-card {
  border-radius: 15px;
  background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
  border: none;
}

.inspiration-content {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 20px;
}

.inspiration-content i {
  font-size: 2.5em;
  color: #ff6b6b;
}

.inspiration-text h3 {
  margin: 0 0 10px 0;
  color: #d63031;
  font-weight: 600;
}

.inspiration-text p {
  margin: 0;
  font-size: 1.1em;
  color: #2d3436;
  font-weight: 500;
}

.ai-assistant-section {
  margin-bottom: 30px;
}

.ai-card {
  border-radius: 15px;
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
  border: none;
}

.ai-content {
  display: flex;
  gap: 20px;
  padding: 25px;
}

.ai-avatar {
  flex-shrink: 0;
  width: 60px;
  height: 60px;
  background: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.ai-avatar i {
  font-size: 1.8em;
  color: #74b9ff;
}

.ai-message {
  flex: 1;
}

.ai-greeting {
  font-size: 1.3em;
  font-weight: 600;
  color: #2d3436;
  margin-bottom: 15px;
}

.ai-question {
  font-size: 1.1em;
  color: #636e72;
  margin-bottom: 15px;
}

.ai-suggestions {
  list-style: none;
  padding: 0;
  margin-bottom: 20px;
}

.ai-suggestions li {
  padding: 8px 0;
  color: #2d3436;
  font-weight: 500;
}

.ai-input {
  margin-bottom: 15px;
}

.ai-response {
  padding: 15px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 10px;
  border-left: 4px solid #74b9ff;
}

.ai-response p {
  margin: 0;
  color: #2d3436;
  line-height: 1.5;
}

/* AI加载动画 */
.ai-loading {
  padding: 20px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 10px;
  border-left: 4px solid #ffd700;
  margin-bottom: 15px;
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.loading-dots {
  display: flex;
  gap: 8px;
}

.loading-dots span {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: linear-gradient(135deg, #74b9ff, #0984e3);
  animation: loadingBounce 1.4s ease-in-out infinite both;
}

.loading-dots span:nth-child(1) {
  animation-delay: -0.32s;
}

.loading-dots span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes loadingBounce {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1.2);
    opacity: 1;
  }
}

.loading-text {
  margin: 0;
  color: #2d3436;
  font-weight: 500;
  text-align: center;
  font-size: 1.1em;
}

/* AI错误提示 */
.ai-error {
  padding: 15px;
  background: rgba(255, 235, 238, 0.9);
  border-radius: 10px;
  border-left: 4px solid #ff6b6b;
  margin-bottom: 15px;
}

.ai-error p {
  margin: 0;
  color: #d63031;
  font-weight: 500;
  line-height: 1.5;
}

.weather-loading {
  padding: 20px;
}

/* 日期导航样式 */
.date-navigation {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-left: auto;
}

.date-display {
  font-weight: 600;
  color: #409EFF;
  font-size: 1.1em;
  min-width: 120px;
  text-align: center;
}

.date-navigation .el-button {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #f0f9ff;
  border: 2px solid #409EFF;
  color: #409EFF;
  transition: all 0.3s ease;
}

.date-navigation .el-button:hover:not(:disabled) {
  background: #409EFF;
  color: white;
  transform: scale(1.1);
}

.date-navigation .el-button:disabled {
  background: #f5f5f5;
  border-color: #dcdfe6;
  color: #c0c4cc;
  cursor: not-allowed;
}

.date-navigation .el-button i {
  font-size: 14px;
}
</style>
